package com.example.materialviewpagerdemo;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.materialviewpagerdemo.Presenter.CurrentDataController;
import com.example.materialviewpagerdemo.bean.CurrentData;
import com.example.materialviewpagerdemo.bean.ListViewModel;
import com.example.materialviewpagerdemo.bean.StaticData;
import com.example.materialviewpagerdemo.util.ChartUtil;
import com.example.materialviewpagerdemo.util.LoadingUtil;
import com.example.materialviewpagerdemo.view.CommonPopupWindow;
import com.example.materialviewpagerdemo.view.PopRecyclerviewAdapter;
import com.github.florent37.materialviewpager.MaterialViewPagerHelper;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class DataAnalysisFragment extends Fragment {
    @BindView(R.id.item_img)
    ImageView itemImg;
    @BindView(R.id.data_name)
    TextView dataName;
    @BindView(R.id.data_content)
    TextView dataContent;
    @BindView(R.id.card_view_part1)
    CardView cardViewPart1;
    @BindView(R.id.lineChart_name)
    TextView lineChartName;
    @BindView(R.id.lineChart)
    LineChart lineChart;
    @BindView(R.id.card_view)
    CardView cardView;
    @BindView(R.id.barchart_name)
    TextView barchartName;
    @BindView(R.id.chart_pm_one)
    BarChart chartPmOne;
    @BindView(R.id.card_view_barchart)
    CardView cardViewBarchart;
    Unbinder unbinder;
    @BindView(R.id.materialScrollView)
    NestedScrollView materialScrollView;

    private ZLoadingDialog dialog;
    ListViewModel listViewModel;
    List<Entry> list = new ArrayList<>();
    List<BarEntry> barlist = new ArrayList<>();
    LoadingUtil loadingUtil;

    //下面三行是在popupwindow中使用到的控件，在加载fragment的时候就对其进行初始化 initpop（）
    private CommonPopupWindow popupWindow;
    private View parentView;
    private RecyclerView recyclerView;

    //存储显示在pop中的数据
    String[] popArray=new String[13];
    //用于记录position，初始的时候默认是空气温度1，position是3
    private static int positionDataAnalysis=3;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.analysis_layout, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        dialog = new ZLoadingDialog(DataAnalysisFragment.this.getActivity());
        MaterialViewPagerHelper.registerScrollView(getActivity(),materialScrollView);
        firstInitData();
    }

    public void firstInitData() {
        //第一次将顶部的cardView初始化
        listViewModel = new ListViewModel();
        listViewModel.setDataName("空气温度1");
        listViewModel.setImgId(R.drawable.ic_airtem);

        //设置pop显示的数组
        popArray=this.getActivity().getResources().getStringArray(R.array.dataTypeName);
        //初始化Popupwindow
        initPop();
        //设置cardview的点击事件
        cardViewListenser();

        //设置统计图的名字
        setRepeatName("空气温度1");

        //显示正在加载
        dialog=new ZLoadingDialog(getActivity());
        loadingUtil=new LoadingUtil(dialog);
        loadingUtil.showDialog();

        //获得数据 并显示
        getCurrentData();
        getDataList(7);
    }

    private void cardViewListenser()
    {
        cardViewPart1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.getPopupWindow().setAnimationStyle(R.style.animAlpha);
                popupWindow.showAtLocation(parentView,Gravity.CENTER,0,0);
                WindowManager.LayoutParams layoutParams=DataAnalysisFragment.this.getActivity().getWindow().getAttributes();
                layoutParams.alpha=0.3f;
                DataAnalysisFragment.this.getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                DataAnalysisFragment.this.getActivity().getWindow().setAttributes(layoutParams);

            }
        });
    }

    //初始化pop以及显示在其上的recyclerview
    public void initPop()
    {
//      用parentView=LayoutInflater.from(getContext()).inflate(R.layout.activity_main,null);或下面这行代码
//      都可以获得对应的view

        parentView=getActivity().findViewById(R.id.drawer_layout);

        popupWindow=new CommonPopupWindow(this.getActivity(),R.layout.text_popup_layout,
                ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT) {
            @Override
            protected void initView() {
                View view=getContentView();
//                recyclerView初始化
                recyclerView=view.findViewById(R.id.recycler);
                recyclerView.setLayoutManager(new GridLayoutManager(DataAnalysisFragment.this.getActivity(),2));
                PopRecyclerviewAdapter homeAdapter=new PopRecyclerviewAdapter(DataAnalysisFragment.this.getActivity(),popArray);
                homeAdapter.setRecyclerViewListener(new PopRecyclerviewAdapter.RecyclerViewListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Log.i("xianshi", "onItemClick: "+position);
                        positionDataAnalysis=position;
                        setRepeatName(popArray[position]);
                        popupWindow.getPopupWindow().dismiss();
                        loadingUtil.showDialog();
                        //清空list，barlist中的数据
                        list.clear();
                        barlist.clear();

                        //获得数据 并显示
                        getCurrentData();
                        getDataList(7);
                    }
                });
                recyclerView.setAdapter(homeAdapter);
            }

            @Override
            protected void initEvent()
            {
                
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            protected void initWindow() {
                super.initWindow();
                PopupWindow instance=getPopupWindow();
                instance.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp=getActivity().getWindow().getAttributes();
                        lp.alpha=1.0f;
                        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                        getActivity().getWindow().setAttributes(lp);
                    }
                });
            }
        };
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public static Fragment newInstance() {
        return new DataAnalysisFragment();
    }

    public void getCurrentData() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(StaticData.url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        CurrentDataController currentDataController = retrofit.create(CurrentDataController.class);
        Call<CurrentData> currentDataCall = currentDataController.queryOne();
        currentDataCall.enqueue(new Callback<CurrentData>() {
            @Override
            public void onResponse(Call<CurrentData> call, Response<CurrentData> response) {
                try {

                    listViewModel.setDataContent(response.body().getAirTemp1() + "℃");
                    switch (positionDataAnalysis)
                    {
                        case 0:
                            listViewModel.setDataName("风速");
                            listViewModel.setImgId(R.drawable.ic_fengsu);
                            listViewModel.setDataContent(response.body().getFengsu() + "m/s");
                            break;
                        case 1:
                            listViewModel.setDataName("风向");
                            listViewModel.setImgId(R.drawable.ic_fengxiang);
                            listViewModel.setDataContent(toChinese(response.body().getFengxiang()));
                            break;
                        case 2:
                            listViewModel.setDataName("光照强度");
                            listViewModel.setImgId(R.drawable.ic_sunshine);
                            listViewModel.setDataContent(response.body().getSunLight() + "kLux");
                            break;
                        case 3:
                            listViewModel.setDataName("空气温度1");
                            listViewModel.setImgId(R.drawable.ic_airtem);
                            listViewModel.setDataContent(response.body().getAirTemp1() + "℃");
                            break;
                        case 4:
                            listViewModel.setDataName("空气湿度1");
                            listViewModel.setImgId(R.drawable.ic_airhum);
                            listViewModel.setDataContent(response.body().getAirHumi1() + "%");
                            break;
                        case 5:
                            listViewModel.setDataName("土壤湿度1");
                            listViewModel.setImgId(R.drawable.ic_soilhum);
                            listViewModel.setDataContent(response.body().getSoilHumi1() + "%");
                            break;
                        case 6:
                            listViewModel.setDataName("土壤盐分1");
                            listViewModel.setImgId(R.drawable.ic_soilsalt);
                            listViewModel.setDataContent(response.body().getSoilSalt1() + "dS/m");
                            break;
                        case 7:
                            listViewModel.setDataName("土壤温度1");
                            listViewModel.setImgId(R.drawable.ic_soiltem);
                            listViewModel.setDataContent(response.body().getSoilTemp1() + "℃");
                            break;
                        case 8:
                            listViewModel.setDataName("空气温度2");
                            listViewModel.setImgId(R.drawable.ic_airtem);
                            listViewModel.setDataContent(response.body().getAirTemp2() + "℃");
                            break;
                        case 9:
                            listViewModel.setDataName("空气湿度2");
                            listViewModel.setImgId(R.drawable.ic_airhum);
                            listViewModel.setDataContent(response.body().getAirHumi2() + "RH%");
                            break;
                        case 10:
                            listViewModel.setDataName("土壤湿度2");
                            listViewModel.setImgId(R.drawable.ic_soilhum);
                            listViewModel.setDataContent(response.body().getSoilHumi2() + "%");
                            break;
                        case 11:
                            listViewModel.setDataName("土壤盐分2");
                            listViewModel.setImgId(R.drawable.ic_soilsalt);
                            listViewModel.setDataContent(response.body().getSoilSalt2() + "dS/m");
                            break;
                        case 12:
                            listViewModel.setDataName("土壤温度2");
                            listViewModel.setImgId(R.drawable.ic_soiltem);
                            listViewModel.setDataContent(response.body().getSoilTemp2() + "℃");
                            break;
                    }
                } catch (NullPointerException e) {
                    listViewModel.setDataContent("");
                    Toast.makeText(DataAnalysisFragment.this.getActivity(), "数据获取失败,请检查网络后重试", Toast.LENGTH_SHORT).show();
                }

                dataContent.setText(listViewModel.getDataContent());
                dataName.setText(listViewModel.getDataName());
                itemImg.setImageDrawable(getActivity().getDrawable(listViewModel.getImgId()));
            }

            @Override
            public void onFailure(Call<CurrentData> call, Throwable t) {
                loadingUtil.cancleDialog();
                Toast.makeText(DataAnalysisFragment.this.getActivity(), "连接超时", Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void getDataList(int number) {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(StaticData.url)
                .build();
        CurrentDataController currentDataController = retrofit.create(CurrentDataController.class);
        Call<List<CurrentData>> call = currentDataController.query(number);
        call.enqueue(new Callback<List<CurrentData>>() {
            @Override
            public void onResponse(Call<List<CurrentData>> call, Response<List<CurrentData>> response) {
                if (response.body() != null) {
                    ListIterator<CurrentData> listIterator = null;
                    try {
                        listIterator = response.body().listIterator();
                    }catch (NullPointerException e){
                        return;
                    }
                    int i = 0;
                    while (listIterator.hasNext()) {

                        i++;
                        CurrentData currentData = listIterator.next();
                        addDataList(currentData,i);
                    }

                    Collections.reverse(list);
                    Collections.reverse(barlist);
                    ChartUtil.setChartData(lineChart, list);
                    ChartUtil.setBarChartData(chartPmOne, barlist);
                    //刷新数据,解决数据更新后界面不会自动刷新的问题，此处因为时间问题，比较匆忙，可以重构，改善代码结构
                    lineChart.notifyDataSetChanged();
                    chartPmOne.notifyDataSetChanged();
                    lineChart.invalidate();
                    chartPmOne.invalidate();
                    //取消动画
                    loadingUtil.cancleDialog();
                }
            }

            @Override
            public void onFailure(Call<List<CurrentData>> call, Throwable t) {
                loadingUtil.cancleDialog();
                System.out.println("失败");
            }
        });
    }


    public void addDataList(CurrentData currentData,int i){
        Entry entry=null;
        BarEntry barEntry=null;
        i=8-i;
        //此处受到position的影响，position期初默认3，后来随着点击事件改变
        switch (positionDataAnalysis) {
            case 0:
                entry = new Entry(i, ChartUtil.toFloat(currentData.getFengsu()), ChartUtil.praseData(currentData.getDataTime()));
                barEntry = new BarEntry(i, ChartUtil.toFloat(currentData.getFengsu()), ChartUtil.praseData(currentData.getDataTime()));
                break;
            case 1:
                entry = new Entry(i, ChartUtil.toFloat(currentData.getFengxiang()), ChartUtil.praseData(currentData.getDataTime()));
                barEntry = new BarEntry(i, ChartUtil.toFloat(currentData.getFengxiang()), ChartUtil.praseData(currentData.getDataTime()));

                break;
            case 2:
                entry = new Entry(i, ChartUtil.toFloat(currentData.getSunLight()), ChartUtil.praseData(currentData.getDataTime()));
                barEntry = new BarEntry(i, ChartUtil.toFloat(currentData.getSunLight()), ChartUtil.praseData(currentData.getDataTime()));

                break;
            case 3:
                entry = new Entry(i, ChartUtil.toFloat(currentData.getAirTemp1()), ChartUtil.praseData(currentData.getDataTime()));
                barEntry = new BarEntry(i, ChartUtil.toFloat(currentData.getAirTemp1()), ChartUtil.praseData(currentData.getDataTime()));

                break;
            case 4:
                entry = new Entry(i, ChartUtil.toFloat(currentData.getAirHumi1()), ChartUtil.praseData(currentData.getDataTime()));
                barEntry = new BarEntry(i, ChartUtil.toFloat(currentData.getAirHumi1()), ChartUtil.praseData(currentData.getDataTime()));

                break;
            case 5:
                entry = new Entry(i, ChartUtil.toFloat(currentData.getSoilHumi1()), ChartUtil.praseData(currentData.getDataTime()));
                barEntry = new BarEntry(i, ChartUtil.toFloat(currentData.getSoilHumi1()), ChartUtil.praseData(currentData.getDataTime()));

                break;
            case 6:
                entry = new Entry(i, ChartUtil.toFloat(currentData.getSoilSalt1()), ChartUtil.praseData(currentData.getDataTime()));
                barEntry = new BarEntry(i, ChartUtil.toFloat(currentData.getSoilSalt1()), ChartUtil.praseData(currentData.getDataTime()));

                break;
            case 7:

                entry = new Entry(i, ChartUtil.toFloat(currentData.getSoilTemp1()), ChartUtil.praseData(currentData.getDataTime()));
                barEntry = new BarEntry(i, ChartUtil.toFloat(currentData.getSoilTemp1()), ChartUtil.praseData(currentData.getDataTime()));

                break;
            case 8:
                entry = new Entry(i, ChartUtil.toFloat(currentData.getAirTemp2()), ChartUtil.praseData(currentData.getDataTime()));
                barEntry = new BarEntry(i, ChartUtil.toFloat(currentData.getAirTemp2()), ChartUtil.praseData(currentData.getDataTime()));

                break;
            case 9:
                entry = new Entry(i, ChartUtil.toFloat(currentData.getAirHumi2()), ChartUtil.praseData(currentData.getDataTime()));
                barEntry = new BarEntry(i, ChartUtil.toFloat(currentData.getAirHumi2()), ChartUtil.praseData(currentData.getDataTime()));

                break;
            case 10:
                entry = new Entry(i, ChartUtil.toFloat(currentData.getSoilHumi2()), ChartUtil.praseData(currentData.getDataTime()));
                barEntry = new BarEntry(i, ChartUtil.toFloat(currentData.getSoilHumi2()), ChartUtil.praseData(currentData.getDataTime()));

                break;
            case 11:
                entry = new Entry(i, ChartUtil.toFloat(currentData.getSoilSalt2()), ChartUtil.praseData(currentData.getDataTime()));
                barEntry = new BarEntry(i, ChartUtil.toFloat(currentData.getSoilSalt2()), ChartUtil.praseData(currentData.getDataTime()));

                break;
            case 12:
                entry = new Entry(i, ChartUtil.toFloat(currentData.getSoilTemp2()), ChartUtil.praseData(currentData.getDataTime()));
                barEntry = new BarEntry(i, ChartUtil.toFloat(currentData.getSoilTemp2()), ChartUtil.praseData(currentData.getDataTime()));

                break;
        }
        list.add(entry);
        barlist.add(barEntry);

    }


    public void setRepeatName (String name){
        lineChartName.setText(name + "-折线图");
        barchartName.setText(name + "-柱状图");
    }

    private String toChinese(String stringAngle){
        double angle=Double.parseDouble(stringAngle);
        if (angle>=0&&angle<22.5)
            return "北风";
        if (angle>=22.5&&angle<67.5)
            return "东北风";
        if (angle>=67.5&&angle<112.5)
            return "东风";
        if (angle>=112.5&&angle<157.5)
            return "东南风";
        if (angle>=157.5&&angle<202.5)
            return "南风";
        if (angle>=202.5&&angle<247.5)
            return "西南风";
        if (angle>=247.5&&angle<292.5)
            return "西风";
        if (angle>=292.5&&angle<337.5)
            return "西北风";
        if (angle>=337.5&&angle<=360)
            return "北风";
        return "参数错误";
    }
}
